<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class cartController extends Controller
{
    
     public function __construct()
        {
            $this->middleware('homelogin');
        }
    public function index(Request $request)
    {

        $data = DB::table('cart')
        ->leftJoin('goods','goods.gid','=','cart.gid')
        ->where('uid',session('homeM')->uid)
        ->get();
        $cnt = DB::table('cart')
        ->select(DB::raw('count(cid) as cnt'))
        ->where('uid',session('homeM')->uid)
        ->first();
        $sum = 0;
        foreach($data as $k => $v)
        {
            $sum += $v -> price * $v -> count;
        }
    	return view('home.cart.index',['data' => $data,'sum' => $sum,'cnt'=>$cnt]);
    }

    public function insert(Request $request)
    {
       $data = $request -> except('_token');
       $data['uid'] = session('homeM')->uid;
       $res = DB::table('cart')->insert($data);

       if($res)
        {
            return redirect('/home/good/list'.'/'.$data['gid']) -> with(['info' => '添加成功成功']);
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }
    }

    public function delete($cid)
    {
    	
    	$res = DB::table('cart')
    	  ->where('cid',$cid)
    	  ->delete();
    	if($res)
    	{
    		return redirect('/home/cart/index') -> with(['info' => '删除成功']);
    	}else
		{
			return back() -> with(['info' => '删除失败']);
		}
    }

}
